<?php

namespace frontend\controllers\restful;

use common\models\Cart;
use Yii;
use yii\rest\Controller;

class CartController extends Controller
{

    public function actionIndex()
    {
//        $cart = Cart::find()->asArray()->joinWith('product')->where(['and',['user_id'=>Yii::$app->user->identity->id],['<>','product_name',null]])->createCommand()->getRawSql();
        //筛选时要保证商品ID对应的商品记录是存在的
        $cart = Cart::find()->asArray()->joinWith('product')->where(['and',['user_id'=>Yii::$app->user->identity->id],['<>','product_name','']])->all();
        return $cart;
    }

    /**
     * @return array
     * @throws \Exception
     * @throws \Throwable
     * @throws \yii\base\InvalidConfigException
     * @throws \yii\db\StaleObjectException
     */
    public function actionUpdate()
    {
        /**
         * $params格式规范：
         * product_id:"1" 商品ID
         * user_id:"12" 用户ID
         */
        $params = Yii::$app->request->getBodyParams();
        //查询该用户是否存在该商品的购物车
        $cart = Cart::findOne(['user_id'=>Yii::$app->user->identity->getId(),'product_id'=>$params['product_id']]);
        //如果用户购物车表中已经存在该商品记录时的加减购物车
        if($cart){
            switch ($params['countType']){
                //当为增加购物车商品数量时
                case 'add':
                    $cart->updateCounters(['quantity' => 1]);
                    break;
                //当为减少购物车商品数量时
                case 'sub':
                    $cart->updateCounters(['quantity' => -1]);
                    //当购物车商品数量小于0时，在数据表中删除该条记录
                    if($cart->quantity <= 0)
                        $cart->delete();
                    break;
                default:
                    break;
            }
        //如果用户购物车中不存在该商品记录，则新增一条记录
        }elseif($params['countType'] === 'add'){
            $cart = new Cart();
            $cart->attributes = [
                'user_id'=>Yii::$app->user->identity->id,
                'product_id'=>$params['product_id'],
                'quantity'=>1
            ];
            $cart->save();
        }
        return ['quantity'=>$cart->quantity];
    }

    /**
     * @param $action
     * @return bool
     * @throws \yii\web\BadRequestHttpException
     */
    public function beforeAction($action)
    {
        if(Yii::$app->user->isGuest)
        {
            //101表示未登录
            $res = ['status'=>'101'];
            echo json_encode($res);
            return false;
        }
        return parent::beforeAction($action); // TODO: Change the autogenerated stub
    }
}